//
//  PGFileManager.m
//  youqu
//
//  Created by 彭鹏 on 16/10/3.
//  Copyright © 2016年 pengpeng. All rights reserved.
//

#import "PGFileManager.h"

@implementation PGFileManager


/**
 获取文件大小
 
 @param fileDirectory 文件目录
 
 */
+ (void)getFileSize:(NSString *)fileDirectory completeBlock:(void(^)(NSUInteger fileSize))complete {
    __block NSUInteger size = 0;

    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isDirectory;
        BOOL fileExist = [fileManager fileExistsAtPath:fileDirectory isDirectory:&isDirectory];
        if (!isDirectory || !fileExist) {
            NSException *e = [NSException exceptionWithName:@"fileError:" reason:@"文件不存在或者是空文件目录" userInfo:nil];
            [e raise];
        }
        
        
        
        NSDirectoryEnumerator *fileEnumerator = [fileManager enumeratorAtPath:fileDirectory];
        for (NSString *fileName in fileEnumerator) {
            NSString *filePath = [fileDirectory stringByAppendingPathComponent:fileName];
            
            //判断是否是文件夹
            BOOL isDirectory;
            [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
            if (isDirectory) continue;
            
            //过滤掉系统隐藏文件
            if ([filePath containsString:@".DS_Store"]) continue;
            
            NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
            size += [attrs fileSize];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            complete(size);
        });
        
    });
//    return size;
    
}

/**
 删除文件
 
 @param fileDirectory 文件目录
 */
+ (void)removeFile:(NSString *)fileDirectory {
    
    
    NSFileManager *fileManger = [NSFileManager defaultManager];
    BOOL isDirectory;
    BOOL fileExist = [fileManger fileExistsAtPath:fileDirectory isDirectory:&isDirectory];
    if (!isDirectory || !fileExist) {
        NSException *e = [NSException exceptionWithName:@"fileError:" reason:@"文件不存在或者是空文件目录" userInfo:nil];
        [e raise];
    }
    
    [fileManger removeItemAtPath:fileDirectory error:nil];
    [fileManger createDirectoryAtPath:fileDirectory
          withIntermediateDirectories:YES
                           attributes:nil
                                error:NULL];
}

@end
